//
//  PostPicViewController.m
//  LiveDailyNews
//
//  Created by smu on 11-7-20.
//  Copyright 2011年 duk. All rights reserved.
//

#import "PostPicViewController.h"
#import "BrokeViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "Constant.h"


@implementation PostPicViewController
//@synthesize imageView;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        resetSelect = [[UIBarButtonItem alloc] initWithTitle:@"上传" 
                                                       style:UIBarButtonItemStyleBordered
                                                      target:self action:@selector(postAction:)];
        
        [[self navigationItem] setRightBarButtonItem:resetSelect];
        
        
    }
    return self;
}

- (void)dealloc
{
    [sheet release]; 
    [imageView release];
    [takePictureButton release];
    [selectFromCameraRollButton release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
                      
- (void)postAction:(id)sender
{
    NSLog(@"%@",textView.text);
    resetSelect.enabled = NO;
    
    
//    //禁止用户操作界面
//    UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"上传中，请等待！" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease];
//    [self.view addSubview:alertView];
//    [alertView show];
//    [alertView addSubview:spinner];
    
    [spinner startAnimating];
    
    
    //上传图片
    NSData *imageData = UIImageJPEGRepresentation(postImage, 90);
    // setting up the request object now
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:POST_IMAGE]];
	[request setHTTPMethod:@"POST"];
    
    
    /*
	 add some header info now
	 we always need a boundary when we post a file
	 also we need to set the content type
	 
	 You might want to generate a random boundary.. this is just the same 
	 as my output from wireshark on a valid html post
     */
	NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
	NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
	[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
	
	/*
	 now lets create the body of the post
     */
	NSMutableData *body = [NSMutableData data];
	[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];	
	[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"file\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
	[body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"par\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@",textView.text] dataUsingEncoding:NSUTF8StringEncoding]];  //上传字符串
	[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
	// setting the body of the post to the reqeust
	[request setHTTPBody:body];
	
	// now lets make the connection to the web
	NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@",returnString);
 
    [spinner stopAnimating];
    resetSelect.enabled = YES;

//    [spinner release];
//    [alertView removeFromSuperview];
//    [alertView release];
    

    
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    
    
    [self sheetShow];
    UIView *contentView = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
    contentView.autoresizesSubviews = YES;
    self.view = contentView;
    [self.view setBackgroundColor:[UIColor clearColor]];
    
    scrollView = [[UIScrollView alloc] initWithFrame:
                  CGRectMake(0, 0, contentView.bounds.size.width, contentView.bounds.size.height - 44)];
    scrollView.scrollEnabled = YES;
    scrollView.alwaysBounceVertical = YES;
    scrollView.delegate = self;
    [self.view addSubview:scrollView];
    
    
    backgroundButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, contentView.bounds.size.width, contentView.bounds.size.height)];
    [backgroundButton setBackgroundColor:[UIColor colorWithHue:0.0 saturation:0.0 brightness:0.0 alpha:0]];
    [backgroundButton addTarget:self action:@selector(backgrdClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [scrollView addSubview:backgroundButton];
    
    
    yOpenKB = self.view.frame.origin.y-130;
    yCloseKB = self.view.frame.origin.y;
    
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, contentView.bounds.size.width-20, 200)];
    //将图层的边框设置为圆脚
    imageView.layer.cornerRadius = 8;
    imageView.layer.masksToBounds = YES;
    //给图层添加一个有色边框
    imageView.layer.borderWidth = 2;
    imageView.layer.borderColor = [[UIColor colorWithRed:0.09 green:0.09 blue:0.1 alpha:1] CGColor];
    
    UIImage *initImage = [UIImage imageNamed:@"Default.png"];
    imageView.image = initImage;
    [scrollView addSubview:imageView];
    
    
    
    
    
    selectPicButton = [[UIButton alloc] initWithFrame:CGRectMake(30, 210, 100, 25)];
    [selectPicButton setTitle:@"重新选择" forState:UIControlStateNormal];
    //定义按钮标题字体格式
    [selectPicButton.titleLabel setFont:[UIFont boldSystemFontOfSize:20]];
    [selectPicButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //定义按钮背景图片
    [selectPicButton setBackgroundImage:[[UIImage imageNamed:@"Icon.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0] forState:UIControlStateNormal];
    //添加点击按钮所执行的程式
    [selectPicButton addTarget:self action:@selector(sheetShow) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:selectPicButton];
    
    
    UILabel *labelText = [[UILabel alloc] initWithFrame:CGRectMake(10, 240, contentView.bounds.size.width-20, 20)];
    labelText.text = @"爆料内容:";
    
    [scrollView addSubview:labelText];
    
    textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 265, contentView.bounds.size.width-40, 120)];
    textView.backgroundColor = [UIColor lightGrayColor];
    textView.text = @"请点击此处输入要爆料的信息！";
    textView.layer.cornerRadius = 5;
    textView.layer.masksToBounds = YES;
    textView.layer.borderWidth = 2;
    textView.layer.borderColor = [[UIColor colorWithRed:0.09 green:0.05 blue:0.1 alpha:1] CGColor];
    textView.delegate = self;

    
    
    [scrollView addSubview:textView];
    

    spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    // I do this because I'm in landscape mode        
    [spinner setCenter:CGPointMake(130, 70)];
    // spinner is not visible until started
//    [self.view addSubview:spinner];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

//关闭键盘
-(void)backgrdClick:(id)sender
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    self.view.frame = CGRectMake(self.view.frame.origin.x, yCloseKB, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
    [textView resignFirstResponder];
}
     
- (void)sheetShow
{
    //检查应用程序所在的设备是否有照相机
    if (![UIImagePickerController isSourceTypeAvailable:
          UIImagePickerControllerSourceTypeCamera]) {
        //隐藏两个照相相关的按钮
        
        
        sheet = [[UIActionSheet alloc] initWithTitle:@"获取图片" 
                                            delegate:self
                                   cancelButtonTitle:@"取消" 
                              destructiveButtonTitle:nil 
                                   otherButtonTitles:@"从相册中选择", nil];
        
    } else {
        sheet = [[UIActionSheet alloc] initWithTitle:@"获取图片" 
                                            delegate:self
                                   cancelButtonTitle:@"取消" 
                              destructiveButtonTitle:nil 
                                   otherButtonTitles:@"从相册中选择",@"从相机中选择", nil];
    }
    [sheet showFromRect:CGRectMake(0, 0, 320, 480) inView:self.view animated:YES]; 
}
                       

- (void)viewDidUnload
{
//    self.imageView = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark -
#pragma mark - UITextView
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    self.view.frame = CGRectMake(self.view.frame.origin.x, yOpenKB, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}


#pragma mark -
#pragma mark ActionSheet Delegate Methods
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex) {
//        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    switch (buttonIndex) {
        case 0:
            [self selectExistingPicture];
            break;
        default:
            [self getCameraPicture:self];
            break;
    }
}



#pragma mark -
#pragma mark UIImagePicker
- (void)getCameraPicture:(id)sender
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera ;
    //呈现图像选择器并释放实例
    [self presentModalViewController:picker animated:YES];
    [picker release];
}

//允许用户从照片库中取得图片
- (void)selectExistingPicture
{
    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:picker animated:YES];
    } else {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Error accessing photo library" 
                              message:@"Device does no support a photo library" 
                              delegate:nil 
                              cancelButtonTitle:@"Drat" 
                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}
#pragma mark -
//用户完成使用图片选择器时调用，用户选择一幅图片之后也会调用此方法，无论使用哪种源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    ////////************************************
    
    
    //*********************
    postImage = image;
    imageView.image = image;
    //让选取器解除自身，以使用户返回到应用程序视图
    [picker dismissModalViewControllerAnimated:YES];
}

//用户取消，不需做其他事情，只关闭图像选取器，否则他会一直在那挡住应用程序视图
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}

@end
